<template>
    <div class="page-edit">
        <div class="edit-wrap">
            <!-- <div class="header-title">
                基本信息
            </div> -->
            <el-form ref="editRef" :model="formData" :rules="formRule" :label-width="118" size="large">
                <div class="form-box">
                    
                    <div class="box-content">
                        <el-form-item label="专题名称" prop="name">
                            <el-input 
                                class="lesson-name"
                                show-word-limit 
                                maxlength="50" 
                                type="text" 
                                v-model="formData.name"
                                placeholder="请输入名称，最多50个字" 
                                style="width: 915px;">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="专题分类" prop="type">
                            <el-select size="large" class="srt-select" popper-class="srt-select-popper"  v-model="formData.type" placeholder="请选择" style="width:460px">
                                <el-option v-for="item in categories" :label="item.name"
                                    :value="item.key" :key="item.key" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="学段学科年级" prop="stageSubjectGrade">
                            <stage-subject ref="ssRef" v-model:selectedData="formData.stageSubjectGrade" :placeholder="'请选择学段学科年级'" style="width:460px">
                            </stage-subject>
                        </el-form-item>
                        <el-form-item label="起止时间" prop="datetime">
                            <el-date-picker
                                class="date-picker"
                                v-model="formData.startTime"
                                type="datetime"
                                placeholder="请选择开始时间"
                            >
                            </el-date-picker>
                            <span style="margin:0 20px;">至</span>
                            <el-date-picker
                                class="date-picker"
                                v-model="formData.endTime"
                                type="datetime"
                                placeholder="请选择结束时间"
                            />
                        </el-form-item>
                        <el-form-item label="学年" prop="schoolYearId">
                            <el-select 
                                v-model="formData.schoolYearId"
                                :class="['srt-select', {'srt-clear-select': formData.schoolYearId}]"
                                popper-class="srt-select-popper" 
                                no-data-text="暂无数据~"
                                :teleported="false"
                                :clearable="true"
                                suffix-icon="CaretBottom"
                                style="width: 460px;"
                            >   
                                <el-option
                                v-for="item in yearOptions"
                                :key="item.id"
                                :label="item.optionName"
                                :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="专题封面" prop="picUrl">
                            <div class="w800">
                                <select-cover :data="getCovers(covers)" :cur="formData.picUrl" :configWidth="320" :configHeight="180"
                                    @select-cover="onSelectCover">
                                </select-cover>
                                <div class="img-tip">图片建议尺寸 450 × 250px，支持 jpg、jpeg、png、webp 格式，图片大小不超过 2M</div>
                            </div>
                        </el-form-item>
                    </div>
                </div>
            </el-form>
        </div>
        <div class="submit">
            <el-button class="srt-el-button srt-el-button--cancel srt-el-button-h36 w120" type="" @click="goBack()">取消</el-button>
            <el-button  class="srt-el-button srt-el-button--primary srt-el-button-h36 w120"  @click="save('editRef')" type="primary">下一步</el-button>
        </div>
    </div>
</template>
<script setup>
// import SelectCover from '../components/select-cover.vue';
import SelectCover from '@/views/create/part/select-cover.vue';
import StageSubject from '@/components/stage-subject/stage-subject-grade.vue';
import { ref, computed, watch, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useStore } from 'vuex';

import { queryToJson } from '@/lib/tools';
import { pageJump } from '@/global/location-transfer'
import { jumpHref } from '@/router/jumpHref';

import { categories, covers } from './static.js'

const router = useRouter();
const route = useRoute();
const store = useStore();
const emit = defineEmits(['update-info', 'set-step'])
const props = defineProps({
    moocTopic: {
        type: Object,
        default: () => {}
    }
})
const currentUser = computed(() => {
    return store.state.currentUser || {};
})

const watchPath = computed(() => {
    return queryToJson()
})
// 表单数据
let formData = ref({
    bizScene: 'mooc',
    bizSource: 'research_study',
    contentSource: 'mooc',
    name: '', // 专题分类
    type: '', // 专题分类
    stageSubjectGrade: [], // 学段学科年级
    schoolYearId: '',
    schoolYearName: '',
    startTime: '',
    endTime: '',
    picUrl: '',
    gradeDTOList: [], // 年级列表
    year: ''
});
// 校验
const formRule = ref({
    type: [{ required: true, message: '请选择专题分类', trigger: 'change' }],
    name: [
        { required: true, message: '请填写专题名称', trigger: 'blur' },
        { max: 50, message: '专题名称最多50个字', trigger: 'blur' }
    ],
    picUrl: [
        {
            required: true,
            validator: (rule, value, callback) => {
                if (formData.value.picUrl) {
                    callback();
                } else {
                    callback(new Error('请选择封面'));
                }
            },
            trigger: 'change'
        }
    ],
    datetime: [
        {
            required: true,
            validator: (rule, value, callback) => {
                const s = formData.value.startTime && new Date(formData.value.startTime).getTime()
                const e = formData.value.endTime && new Date(formData.value.endTime).getTime()
                if(!formData.value.startTime && !formData.value.endTime){
                    callback(new Error('请选择起止时间'))
                }else if(!formData.value.startTime){
                    callback(new Error('请选择开始时间'))
                }else if(!formData.value.endTime){
                    callback(new Error('请选择结束时间'))
                }else if(s > e){
                    callback(new Error('开始时间不能大于结束时间'))
                }else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    stageSubjectGrade: [
        {
            required: true,
            validator: (rule, value, callback) => {
                console.log('ddddd')
                if (
                    formData.value.stageSubjectGrade &&
                    formData.value.stageSubjectGrade.length > 0
                ) {
                    callback();
                } else {
                    callback(new Error('请选择学段学科'));
                }
            },
            trigger: 'blur'
        }
    ]
    // schoolYearId: [{ required: true, message: '请选择学年', trigger: 'change' }],
});

const editRef = ref(null);

const yearOptions = ref([])

watch(() => watchPath.value, (val) => {
    console.log('watch value', val)
    if(watchPath.value.id) {
        getDetailData()
    }
}, {deep: true, immediate: true})


// 监听获取到用户信息
// watch(() => currentUser.value, async(val) => {
//     if(watchPath.value.id) {
//         getDetailData()
//     }
// }, {deep: true, immediate: true})

// 更新封面列表
function getCovers(templateCovers) {
    if (formData.value.picUrl) {
        let index = templateCovers.findIndex((item) => {
            return item === formData.value.picUrl;
        });
        if (index === -1) {
            templateCovers.push(formData.value.picUrl);
        }
    } else {
        formData.value.picUrl = templateCovers[0]
    }
    return templateCovers || [];
}

// 保存信息
function save() {
    console.log('formData', formData.value, watchPath.value)
    editRef.value.validate((valid) => {
        if (valid) {
            let data = {...formData.value}
            data.startTime = new Date(data.startTime).valueOf()
            data.endTime = new Date(data.endTime).valueOf()
            let tempYear = yearOptions.value.filter((item) => {
                return item.id === data.schoolYearId
            })
            console.log('tempYear', tempYear)
            if(tempYear.length) {
                data.schoolYearName = tempYear[0].periodName
            } else {
                data.schoolYearName = ''
            }
            data.stageSubjectGrade = JSON.stringify(data.stageSubjectGrade)
            if(watchPath.value.id) {
                G_transmit('editMoocTopic', {
                    data
                })
                .then((res) => {
                    G_dispatchEvent('toast', { message: '保存成功', type: 'success'})
                    emit('update-info', {...formData.value})
                    emit('set-step', 2)
                    window.history.replaceState('', '', `?id=${watchPath.value.id}&step=2`);
                })
                .catch((err) => {
                    console.log(err)
                });
            } else {
                G_transmit('createMoocTopic', {
                    data
                })
                .then((res) => {
                    G_dispatchEvent('toast', { message: '保存成功', type: 'success'})
                    emit('update-info', {...formData.value, id: res.data})
                    emit('set-step', 2)
                    window.history.replaceState('', '', `?id=${res.data}&step=2`);
                })
                .catch((err) => {
                    console.log(err)
                });
            }
            
        } else {
            return false;
        }
    });
}

function onSelectCover(url) {
    formData.value.picUrl = url;
}
// 获取编辑信息
function getDetailData() {
    return G_transmit('topicDetail', {
        queries: {
            id: watchPath.value.id
        }
    })
    .then(({ status, data }) => {
        console.log('dddd data', data, currentUser.value)
        if(!data.creatorFlag){
            G_dispatchEvent('toErrorPage', { title: '很抱歉，您暂时没有权限对该慕课进行编辑', code: 500, buttonLabel: '返回', target: getBackUrl()});
            return;
        }
        // if(data.state === -1){
        //     G_dispatchEvent('toErrorPage', { title: '该慕课专题已经被删除', code: 500});
        //     return;
        // }
        Object.keys(formData.value).forEach((item) => {
            if(!['picUrl'].includes(item)){
                formData.value[item] = data[item];
            }
        });
        formData.value = data
        formData.value.stageSubjectGrade = JSON.parse(formData.value.stageSubjectGrade)
        return Promise.resolve(data)
    })
    .catch((err) => {
        // if(err.status.code == '40000001'){
        //     G_dispatchEvent('toErrorPage', { title: '该慕课专题不存在', code: 500});
        // }
        console.log(err, 'err');
    });
}
function getYearOptions() {
    G_transmit('getPeriodYear', {
        name: 'getPeriodYear',
        message: false,
    }).then(({ data, status }) => {
        data.forEach(item => {
            item.optionName = item.periodName
        })
        yearOptions.value = [...data]
    }).catch(err => {
        G_dispatchEvent('toast', { message: err.status.desc, type: 'error'});
    })
}
// 返回课程详情
function goBack(){
    pageJump({
        name: route.name === 'strainMoocTopicCreate' ? 'strainTopicDetail' : 'topicDetail',
        params: {topicId: watchPath.value.id}
    });
}
function getBackUrl() {
    if(route.name === 'strainMoocTopicCreate') {
        return jumpHref.strain.strainTopicDetail(watchPath.value.id);
    } else {
        return jumpHref.strain.topicDetail(watchPath.value.id);
    }
}
// 生命周期钩子函数
onMounted(async() => {
    getYearOptions()
});
</script>
<style lang='scss' scoped>
.page-edit {
    .edit-wrap {
        background-color: #fff;
        padding-top: 24px;
        border-radius: 0 0 4px 4px;
        :deep .form-box {
            // @include box-radius($color: var(--srt-color-white), $radius: 4px, $padding: 0);
            padding-left: 30px;
            box-sizing: border-box;
            .lesson-name{
                .el-input__inner{
                    color: #222222;
                }
            }
            .date-picker{
                width:240px;
                height:40px;
                .el-input__prefix-inner{
                    .el-input__icon{
                        display: none;
                    }
                }
                .el-input__suffix-inner{
                    &:before {
                        content: "\e6a3";
                        font-family: 'iconfont';
                        color: #000;
                    }
                }
            }
            .img-tip{
                font-size: 14px;
                color: #999999;
                line-height: 20px;
                margin-top: -8px;
            }
        }
    }

    // 覆盖element表单的样式
    :deep {
        .el-form {
            .el-form-item {
                margin-bottom: 0;
                padding-bottom: 30px;
                &:last-child{
                    padding-bottom: 40px;
                }
            }
            

            .el-input__inner {
                height: 40px;
            }

            .el-form-item__label {
                padding-right: 20px;
                font-size: 14px;
                color: #666666;
            }
            .sss {
                width: 460px;
                min-height: 40px;
                .ss {
                    line-height: 40px;
                }
            }
        }
    }

    
}
.submit {
    margin-top: 40px;
    text-align: center;
}
.w800 {
    width: 800px;
}
.w120 {
    width: 120px;
}
</style>